# check for ppp connection, if not connected, reconnect again, it also logs the time and status of connection to a log file specified at the beginning.
# How does this script check you are connected to internet or not? by using ping and checking stderr and match two words in it: "unreachable" and "unknown".

The egrep command with option -c counts the number of matches(with POSIX regex here), if it is 0 then we are connected to internet, else, we are not and we have to reconnect again.

*This script is best used by cron, just add it to your cron and have it run every 2-3 minutes.

#!/bin/bash

#here I defined the logfile's location
logfile=/home/anarion/bin/recon-log

#the heart of this script lies right here
#just ping google.com with one packet, pipe it's stderr to egrep and match either of those words
#egrep's -c tells to output the number of matches
status=$(ping -c 1 google.com 2>&1 | egrep -c "\<unknown\>|\<unreachable\>")

if [ $status -eq 0 ]; then

    #the -n says stay in this line after outputting
    #print an empty line
    echo "" >> $logfile
    echo -n "Already Connected - " >> $logfile

    #output date to the logfile
    date >> $logfile

    #exit with success code
    exit 0
fi

#output to log
echo "" >>$logfile
echo -n "Not Connected - " >> $logfile
date >> $logfile

# disconnect all instances of ppp and then reconnect
#not that you cannot have &>> to append both stderr and stdout
#so I redirected stderr to stdout and then appended the stdout to the log
poff -a 2>&1 >> $logfile

#switch dsl-provider with your connection name
pon dsl-provider 2>&1 >> $logfile

exit 0